package cat_hobby

import (
	"cat-collage-backend/internal/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
)

func AddCatsHobby(c *gin.Context, db *gorm.DB) {
	catHobby := &model.CatHobby{}
	id, err := uuid.NewRandom()
	handleError(c, err)
	catHobby.ID = id.String()
	err = c.ShouldBindJSON(catHobby)
	handleError(c, err)
	result := db.Create(catHobby)
	handleError(c, result.Error)
	c.JSON(200, gin.H{"code": http.StatusOK, "message": "操作成功"})
}

func DeleteCatsHobby(c *gin.Context, db *gorm.DB) {
	hobbyIdsJSON, _ := c.GetPostForm("hobbyIds")
	if hobbyIdsJSON == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide hobbyIds"})
		return
	}

	hobbyIds := []string{}

	err := json.Unmarshal([]byte(hobbyIdsJSON), &hobbyIds)
	handleError(c, err)

	result := db.Where("id IN ?", hobbyIds).Delete(&model.CatHobby{})
	handleError(c, result.Error)
	c.JSON(200, gin.H{"code": http.StatusOK, "message": "操作成功", "deletedCount": result.RowsAffected})
}

func handleError(c *gin.Context, e error) {
	if e != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "msg": "操作失败"})
	}
}
